package com.bss.framework;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.bss.command.AbstractCommand;


public class FrontController extends HttpServlet {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(FrontController.class);
	
	
	/**
	 * initialization method for servlet
	 */
	public void init() {		
	}

	/**
	 * The doget method of the servlet
	 * @param request HttpServletRequest object
	 * @param response HttpServletResponse object
    * @throws ServletException
    * @throws IOException
	 */
	protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException,
		java.io.IOException {
		
		//redirect to dopost
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException,
		java.io.IOException {
		
		try {
					
			
			
			Class obj;
			HttpSession session = null;	
			AbstractCommand comobj;
			
			try {
				
				if (session == null) {		
					session = request.getSession();	
					//debug("Event: " + session.getAttribute("Event"));
				}
				
				session.setAttribute("version", "v1.4");
				
				obj = Class.forName("com.bss.command."+session.getAttribute("Event").toString());
			 
				comobj = (AbstractCommand) obj.newInstance();
			
				//debug("Serving: " + session.getAttribute("Event").toString() );
			
				if(comobj.execute(request,session)==false)
				{
					comobj.falseforward(response,session);
				}
				else
				{
					comobj.trueforward(response,session);
				}
				
				
			}			
			 catch (Exception e) {
				 	e.printStackTrace();
				 	String msg = getErrorTrace(e);
					debug("ERROR SERVING 1: \n" + msg);
					response.sendRedirect("login.jsp");
				} 
		}
		catch(Throwable tt) {
			debug("ERROR SERVING 2: "+ tt.getMessage());
			response.sendRedirect("login.jsp");
		}					
	}
	
	private String getErrorTrace(Exception ee) {
		StringBuilder sb = new StringBuilder();
		sb.append( ee.getClass().getName() + ": " + ee.getMessage()  + "\n");
		for(StackTraceElement e: ee.getStackTrace()) {
			sb.append(e.getClassName() + "." + e.getMethodName() + "() at " + e.getLineNumber() + "\n");
		}
		return sb.toString();
	}
	
	public static void debug(Object message) {
		logger.debug(message);
	}
	
	public static void trace(Object message) {
				
	}
	
	public static void error(Object message) {
		logger.error(message);
	}
	
	public static void audit(Object message) {
		logger.debug(message);
	}
	
}
